package com.gmq.mianshi.designModel.testsync;

/**
 *
 * @author gmq
 * @email 2628931@qq.com
 * @date 2017/11/22 22:42
 */
public class SyncFunc {

    // demo1、2
//    public synchronized void func1() {
//        System.out.println(Thread.currentThread().getName() + " is running");
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        System.out.println(Thread.currentThread().getName() + " is stop");
//    }

    // demo3
    public static synchronized void func1() {
        System.out.println(Thread.currentThread().getName() + " is running");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " is stop");
    }

    public static void main(String[] args) {

        NewThread newThread1 = new NewThread();
        NewThread newThread2 = new NewThread();
        NewThread newThread3 = new NewThread();

        newThread1.start();
        newThread2.start();
        newThread3.start();

    }
}

class NewThread extends Thread {

    //Demo1：一个实例的多个线程，一次只能有一个线程进入非静态同步的方法。
//    Thread-2 is running
//    Thread-2 is stop
//    Thread-1 is running
//    Thread-1 is stop
//    Thread-0 is running
//    Thread-0 is stop
//    从结果可见，每次只能有一个线程进入非静态同步的方法。
//    static SyncFunc syncFunc = new SyncFunc();

    // Demo2：多个实例的线程能同时进入非静态同步的方法。
//    Thread-0 is running
//    Thread-1 is running
//    Thread-2 is running
//    Thread-2 is stop
//    Thread-1 is stop
//    Thread-0 is stop
//    从结果可以看出，多个实例的线程同时进入了同步的非静态方法。
//    SyncFunc syncFunc = new SyncFunc();

    // Demo3：多个实例的线程进入静态的同步方法。
//    Thread-0 is running
//    Thread-0 is stop
//    Thread-1 is running
//    Thread-1 is stop
//    Thread-2 is running
//    Thread-2 is stop
//    从结果可以看出，对于同一个对象的多个实例，在进入静态的同步方法时，一次只能有一个类实例进入。
    SyncFunc syncFunc = new SyncFunc();
    @Override
    public void run() {
        syncFunc.func1();
    }

}
